package com.dcjt.firehotcarpad.fragment

import CarStatePool
import LocationPool
import MapOperationEventPool
import NewMessagePool
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocation
import com.amap.api.location.DPoint
import com.amap.api.maps.model.LatLng
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.manager.RxJavaManager
import com.aries.library.fast.module.fragment.FastRefreshLoadFragment
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusTextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.adapter.FunctionButtonAdapter
import com.dcjt.firehotcarpad.adapter.JjdPopwindowAdapter
import com.dcjt.firehotcarpad.adapter.OnJjdClickLisenter
import com.dcjt.firehotcarpad.base.ApiPath
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.entity.*
import com.dcjt.firehotcarpad.helper.CountDownDialogHelper
import com.dcjt.firehotcarpad.helper.DetermineHelper
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.manager.TtsManager
import com.dcjt.firehotcarpad.model.FunctionViewModel
import com.dcjt.firehotcarpad.model.HandleDisasterViewModel
import com.dcjt.firehotcarpad.moudle.NavActivity
import com.dcjt.firehotcarpad.utils.AlertDialogUtil
import com.dcjt.firehotcarpad.utils.LocationType
import com.dcjt.firehotcarpad.utils.StringUtils
import com.google.gson.Gson
import io.reactivex.disposables.CompositeDisposable


class FunctionButtonFragment(private val callback: ((String) -> Unit)) :
    FastRefreshLoadFragment<FunEntity>(), CarStatePool.CarStateChangeObserver,
    LocationPool.LocationChangeObserver, NewMessagePool.NewMessageObserverObserver {
    private lateinit var mAdapter: FunctionButtonAdapter
    lateinit var viewModel: FunctionViewModel
    lateinit var handleViewModel: HandleDisasterViewModel
    private var pop: PopupWindow? = null
    private var jjdrecy_height: Int? = null
    private var dianceNum: Int = 0

    // RxJava 容器 防止内存泄漏
    private val mCompositeDisposable = CompositeDisposable()
    private var carZzxx: CarZZXX? = null
    private var carZZLocation: LatLng? = null
    private var jjdXY_List: ArrayList<JjdItem>? = null
    private var syLocation: LatLng? = null
    private var yqLocation: LatLng? = null
    private var zqdLocation: LatLng? = null
    lateinit var adapter_jjd: JjdPopwindowAdapter
    var ywjq: Boolean = true
    var clzt: String = ""
    var lastZt: String = ""


    companion object {
        fun newInstance(callback: ((String) -> Unit)): FunctionButtonFragment {
            return FunctionButtonFragment(callback)
        }
    }

    override fun getLayoutManager(): RecyclerView.LayoutManager {
        val manager = LinearLayoutManager(mContext)
        manager.orientation = LinearLayoutManager.HORIZONTAL
        return manager
    }

    override fun getContentLayout(): Int = R.layout.fast_layout_multi_status_refresh_recycler
    override fun initView(savedInstanceState: Bundle?) {
        loadData(0)

        CarStatePool.get().registerCarStateObserver(this)
        LocationPool.get().registerLocationObserver(this)
        NewMessagePool.get().registerNewMessageObserver(this)
        viewModel.requestStatusLiveData.observeForever {
            if (it.code == BaseEntity.err) {
                ToastUtil.show("操作失败")
            } else {
                ToastUtil.show("操作成功")
                CarStatePool.get().getCarState(true)
                if (carZzxx != null) {
                    handleViewModel.loadDisasterDetail(carZzxx!!.zqxx!!.id!!)
                }
            }
        }

        handleViewModel =
            ViewModelProviders.of(requireActivity()).get(HandleDisasterViewModel::class.java)
        //营区
        if (!StringUtils.isEmpty(DataManager.getInstance().user.x))
            yqLocation = LatLng(
                DataManager.getInstance().user.y.toDouble(),
                DataManager.getInstance().user.x.toDouble()
            )
        if (yqLocation != null) {
            uploadNavStateAdapter(9)
            MapOperationEventPool.get()
                .sendDispatch(MapEvent(yqLocation!!, LocationType.LOCATION_CAMP, true))
        }
        handleViewModel.getDisasterInfo().observe(this, androidx.lifecycle.Observer { entity ->
            //判断警情信息zqxx是否为空    为空：警情结束，弹出弹框《只有一个车》    不为空：多个车   页面保存
            if (entity != null) {
                if (entity!!.zqxx != null) {
                    carZzxx = entity
                    LoggerManager.e("handleViewModel" + Gson().toJson(carZzxx))
                    CarStatePool.get().setCurrentZqidPage(carZzxx?.zqxx?.id!!)
                    callback("${carZzxx!!.zqxx!!.sfdz}")

                    if (StringUtils.isEmpty(entity!!.zqxx?.gisX)) {
                        showZqxxError(mContext.resources.getString(R.string.car_no_xy_dismiss))
                        return@Observer
                    }
                    //作战位信息
                    if (carZzxx!!.clxx!! != null && !StringUtils.isEmpty(carZzxx!!.clxx!!.gisX))
                        carZZLocation = LatLng(
                            carZzxx!!.clxx!!.gisY!!.toDouble(),
                            carZzxx!!.clxx!!.gisX!!.toDouble()
                        )
                    if (carZZLocation != null) {
                        MapOperationEventPool.get().sendDispatch(
                            MapEvent(
                                carZZLocation!!,
                                LocationType.LOCATION_COMBAT,
                                true
                            )
                        )
                        uploadNavStateAdapter(7)
                    }

                    //金纬度转换
                    //灾情点
                    if (carZzxx!!.zqxx!! != null && !StringUtils.isEmpty(carZzxx!!.zqxx?.gisY))
                        zqdLocation = LatLng(
                            carZzxx!!.zqxx!!.gisY!!.toDouble(),
                            carZzxx!!.zqxx!!.gisX!!.toDouble()
                        )
                    if (zqdLocation != null) {
                        LoggerManager.e("LocationType_send:发送位置")
                        uploadNavStateAdapter(5)

                        LocationType.LOCATION_DISASTER.flag = carZzxx!!.zqxx!!.ajlx!!
                        MapOperationEventPool.get().sendDispatch(
                            MapEvent(
                                zqdLocation!!,
                                LocationType.LOCATION_DISASTER,
                                true
                            )
                        )
                        //自动规划路线
                        MapOperationEventPool.get().sendDispatch(
                            MapEvent(
                                zqdLocation!!,
                                LocationType.LOCATION_DISASTER,
                                false
                            )
                        )
                    }

                    //集结点
                    if (carZzxx!!.jjd!! != null && carZzxx!!.jjd!!.size > 0) {
                        //多个集结点
                        jjdXY_List = carZzxx!!.jjd!!
                    }

                    if (jjdXY_List != null) {
                        uploadNavStateAdapter(6)
                        //分别上集结点
                        jjdXY_List?.forEachIndexed { index, jjdItem ->
                            getJjdPosition(index)?.let {
                                LoggerManager.e("LocationType_send_集结点")
                                MapOperationEventPool.get().sendDispatch(
                                    MapEvent(
                                        it,
                                        LocationType.LOCATION_ASSEMBLY,
                                        true
                                    )
                                )
                            }
                        }

                    }

                    //水源
                    if (carZzxx!!.syxx!! != null && !StringUtils.isEmpty(carZzxx!!.syxx?.gisX))
                        syLocation = LatLng(
                            carZzxx!!.syxx!!.gisY!!.toDouble(),
                            carZzxx!!.syxx!!.gisX!!.toDouble()
                        )
                    if (syLocation != null) {
                        uploadNavStateAdapter(8)
                        LoggerManager.e("LocationType_send_水源")
                        MapOperationEventPool.get()
                            .sendDispatch(MapEvent(syLocation!!, LocationType.LOCATION_WATER, true))
                    }

                    updateCar(carZzxx!!.clxx!!.clzzzt!!)
                    clzt = carZzxx!!.clxx!!.clzzzt!!
                } else {
                    //弹出弹框
                    showZqxxError(mContext.resources.getString(R.string.car_distance_dismiss))
                }
            }

        })


    }

    private fun showZqxxError(str: String) {
        AlertDialogUtil.alertTips(
            requireContext(),
            resources.getString(R.string.tips),
            str,
            {
            },
            {
                //确定
                val intent: Intent = FastStackUtil.getInstance().current.intent
                FastStackUtil.getInstance().current.setResult(ApiPath.RESULT_CODE, intent)
                FastStackUtil.getInstance().current.finish()
            },
            positiveBtn = "确定"
        )
    }

    override fun getAdapter() = FunctionButtonAdapter(null).apply {
        mAdapter = this
    }

    override fun isRefreshEnable(): Boolean {
        return false
    }

    override fun isLoadMoreEnable(): Boolean {
        return false
    }


    override fun loadData(page1: Int) {
        mEasyStatusView.content()
//        mEasyStatusView.loading()
        mRefreshLayout.finishRefresh()
        mAdapter.loadMoreComplete()
        val list: ArrayList<FunEntity> = ArrayList()
        list.add(FunEntity("出动", false, true, LocationType.OUT))
        list.add(FunEntity("到场", false, true, LocationType.ARRIVE))
        list.add(FunEntity("出水", false, true, LocationType.EFFLUENT))
        list.add(FunEntity("停水", false, true, LocationType.WATERSTOP))
        list.add(FunEntity("返队", false, true, LocationType.BACK))
        list.add(FunEntity("灾情导航", false, true, LocationType.LOCATION_DISASTER))
        list.add(FunEntity("集结点导航", false, true, LocationType.LOCATION_ASSEMBLY))
        list.add(FunEntity("作战位导航", false, true, LocationType.LOCATION_COMBAT))
        list.add(FunEntity("水源导航", false, true, LocationType.LOCATION_WATER))
        list.add(FunEntity("营区导航", false, true, LocationType.LOCATION_CAMP))
        list.add(
            FunEntity(
                LocationType.UPLOAD_EMERFENCY.desc,
                true,
                true,
                LocationType.UPLOAD_EMERFENCY
            )
        )
        mAdapter.setNewData(list)
        viewModel = ViewModelProvider(this).get(FunctionViewModel::class.java)
    }

    override fun onItemClicked(
        adapter: BaseQuickAdapter<FunEntity, BaseViewHolder>?,
        view: View?,
        position: Int
    ) {
        val context = requireContext()

        val entity = adapter?.getItem(position)
        entity ?: return
        if (entity != null)
            if (entity.enable) {

                when (entity.btnCommand) {
                    LocationType.OUT,
                    LocationType.ARRIVE,
                    LocationType.EFFLUENT,
                    LocationType.WATERSTOP,
                    LocationType.BACK -> showTipAlert(entity.str, entity.btnCommand.flag)
                    //灾情导航
                    LocationType.LOCATION_DISASTER -> {
                        NavActivity.startNavActivity(
                            FastStackUtil.getInstance().current,
                            zqdLocation!!.latitude,
                            zqdLocation!!.longitude
                        )
                    }
                    //集结点导航
                    LocationType.LOCATION_ASSEMBLY -> {
                        if (jjdXY_List != null)
                            if (jjdXY_List?.size!! > 1) {
                                //弹出pop
                                view?.let { showJjdPopWindow(it, position, jjdXY_List!!) }
                            } else {
                                getJjdPosition(0)?.let {
                                    NavActivity.startNavActivity(
                                        FastStackUtil.getInstance().current,
                                        it!!.latitude,
                                        it!!.longitude
                                    )
                                }

                            }

                    }
                    //作战位导航
                    LocationType.LOCATION_COMBAT -> {
                        NavActivity.startNavActivity(
                            FastStackUtil.getInstance().current,
                            carZZLocation!!.latitude,
                            carZZLocation!!.longitude
                        )

                    }
                    //水源导航
                    LocationType.LOCATION_WATER -> {
                        NavActivity.startNavActivity(
                            FastStackUtil.getInstance().current,
                            syLocation!!.latitude,
                            syLocation!!.longitude
                        )
                    }
                    //营区导航
                    LocationType.LOCATION_CAMP -> {
                        NavActivity.startNavActivity(
                            FastStackUtil.getInstance().current,
                            yqLocation!!.latitude,
                            yqLocation!!.longitude
                        )
                    }
                    //突发情况
                    LocationType.UPLOAD_EMERFENCY -> {
                        ToastUtil.show("发送突发情况消息")
                    }
                    else -> {
                    }
                }

            }
    }

    /**
     * 修改车辆操作
     */
    private fun updateCar(zt: String) {
        lastZt = zt
        var carStatus: Int = 0
        if (zt != null) {
            carStatus = zt.toInt()
        }
        if (carStatus < "03".toInt() && ywjq) {
            uploadCarStateApdata(-1)
        } else {
            when (zt) {
                "03" -> uploadCarStateApdata(0)
                "0302" -> uploadCarStateApdata(1)
                "0303" -> uploadCarStateApdata(2)
                "0304" -> uploadCarStateApdata(3)
                "0305" -> uploadCarStateApdata(4)
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    /**
     * 车辆状态修改adpter布局
     */
    private fun uploadCarStateApdata(position: Int) {
        for (i in 0..4) {
            mAdapter.getItem(i)?.enable = i > position
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mCompositeDisposable.clear()
        CarStatePool.get().unRegisterCarStateObserver(this)
        LocationPool.get().unRegisterLocationObserver(this)
        NewMessagePool.get().unRegisterNewMessageObserver(this)

    }

    /**
     * 修改状态提示框
     */
    fun showTipAlert(zt: String, ztdm: String) {

        if (carZzxx == null) {
            ToastUtil.show("详情数据传递错误，请稍后点击")
            return
        }
        if (ywjq != null)
            AlertDialogUtil.alertTips(requireContext(),
                resources.getString(R.string.tips), "修改车辆状态为   ${zt} ？",
                {
                }, {
                    //进行网络请求---修改车辆状态
                    //在车辆信息中字段判断 ywjq  是否有警情   有： buz_SetClzt      无 buz_SetClzt_wjq （修改状态）
                    viewModel.changeCarStatus(
                        carZzxx!!.zqxx!!.id!!,
                        carZzxx!!.clxx!!.cfCjxxId!!,
                        ztdm,
                        ywjq,
                        mContext
                    )
                }, negativeBtn = "取消", positiveBtn = "确定"
            )

    }

    override fun onCarStateChange(carStateDetail: CarCurrentDetailEntity) {
        ywjq = carStateDetail!!.clxx!!.ywjq!!
        clzt = carStateDetail!!.clxx!!.clzzzt!!
        if (carZzxx!!.zqxx!!.id!! == carStateDetail!!.clxx!!.jqid!!) {
            if (!StringUtils.isEmpty(carStateDetail.clxx?.jqid) && carStateDetail.clxx?.jqid == carZzxx!!.zqxx!!.id!!) {
                updateCar(carStateDetail!!.clxx!!.clzzzt!!)
            }
            LoggerManager.e("handleViewModel_onCarState_Page" + carZzxx!!.zqxx!!.id!!)
            LoggerManager.e("handleViewModel_onCarStateChange:" + carStateDetail.clxx?.jqid)
            handleViewModel.loadDisasterDetail(carZzxx!!.zqxx!!.id!!)
            return
        }
        if (!StringUtils.isEmpty(lastZt) && lastZt.toInt() >= "03".toInt()) {
            //判断
            handleViewModel.loadDisasterDetail(carZzxx!!.zqxx!!.id!!)
        }
    }

    override fun onChange(location: AMapLocation) {
        //距离+ 状态判断是否弹框
        if (!StringUtils.isEmpty(clzt) && ywjq && CarStatePool.get()
                .getZqidGl() == carZzxx!!.zqxx!!.id!!
        ) {
            var nextZt: String = ""
            var ms: String = ""
            when (clzt) {
                //下一步状态为出动
                "01", "02" -> {
                    if (DetermineHelper.getInstance()
                            .isOffCamp(DPoint(location.latitude, location.longitude))
                    ) {
                        ms = "已驶离营区超过${SPConstant.CAR_DISTANCE}米，20秒后系统将自动设置为  出动?"
                        nextZt = "03"
                    } else {
                        return
                    }
                }
                //下一步状态为到场
                "03", "0301" -> {
//                    if (!StringUtils.isEmpty(carZzxx!!.zqxx?.gisX)) {
//                        distance = CoordinateConverter.calculateLineDistance(
//                            DPoint(
//                                location.latitude,
//                                location.longitude
//                            ),
//                            DPoint(
//                                carZzxx!!.zqxx!!.gisY!!.toDouble(),
//                                carZzxx!!.zqxx!!.gisX!!.toDouble()
//                            )
//                        )
//                        if (distance < SPConstant.CAR_DISTANCE.toInt()) {
//                            ms = "距离灾情点不足${SPConstant.CAR_DISTANCE}米，20秒后系统将自动设置为  到场?"
//                            nextZt = "0302"
//                        } else {
//                            return
//                        }
//                    }

                    if (DetermineHelper.getInstance().isArriveScene(
                            DPoint(location.latitude, location.longitude),
                            DPoint(
                                carZzxx!!.zqxx!!.gisY!!.toDouble(),
                                carZzxx!!.zqxx!!.gisX!!.toDouble()
                            )
                        )
                    ) {
                        ms = "距离灾情点不足${SPConstant.CAR_DISTANCE}米，20秒后系统将自动设置为  到场?"
                        nextZt = "0302"
                    } else {
                        return
                    }
                }
                //下一步状态为返队
                "0302", "0303", "0304" -> {
//                    if (!StringUtils.isEmpty(DataManager.getInstance().user.x)) {
//                        distance = CoordinateConverter.calculateLineDistance(
//                            DPoint(
//                                location.latitude,
//                                location.longitude
//                            ),
//                            DPoint(
//                                DataManager.getInstance().user.y.toDouble(),
//                                DataManager.getInstance().user.x.toDouble()
//                            )
//                        )
//                        if (distance < SPConstant.CAR_DISTANCE.toInt()) {
//                            ms = "距离营区不足${SPConstant.CAR_DISTANCE}米，20秒后系统将自动设置为  返队?"
//                            nextZt = "0305"
//                        } else {
//                            return
//                        }
//                    }

                    if (DetermineHelper.getInstance()
                            .isBackCamp(DPoint(location.latitude, location.longitude))
                    ) {
                        ms = "距离营区不足${SPConstant.CAR_DISTANCE}米，20秒后系统将自动设置为  返队?"
                        nextZt = "0305"
                    } else {
                        return
                    }

                }
            }
//            if (!StringUtils.isEmpty(ms)) {
//                //判断时间间隙
//                if (dianceNum!! > 5) {
//                    showAlert(ms, nextZt)
//                }
//                dianceNum++
//            }
            if (!TextUtils.isEmpty(ms))
                showAlert(ms, nextZt)

        }
    }

    private fun showAlert(ms: String, nextZt: String) {
        dianceNum = 0
        CountDownDialogHelper.showCountDownDialog(
            FastStackUtil.getInstance().current,
            "提醒",
            ms,
            "确定",
            callback = {
                viewModel.changeCarStatus(
                    carZzxx!!.zqxx!!.id!!,
                    carZzxx!!.clxx!!.cfCjxxId!!,
                    nextZt,
                    ywjq,
                    mContext
                )
                MapOperationEventPool.get()
                    .sendDispatch(MapEvent(zqdLocation!!, LocationType.LOCATION_DISASTER, false))

            }, cancelCallback = {})
        TtsManager.get().speeckTTs(ms)
    }

    /**
     * 新警情
     */
    override fun onNewDisasterMessage(data: EventEntity.MessageDetailEvent) {
        super.onNewDisasterMessage(data)
        //刷新该页面
        ywjq = true
        lastZt = "0"
        CarStatePool.get().getCarState(true)
        data.zqId?.let { handleViewModel.loadDisasterDetail(it) }
    }

    /**
     * 作战位改变
     */
    override fun onCarLocationChange(data: EventEntity.MessageDetailEvent) {

        NavActivity.startNavActivity(FastStackUtil.getInstance().current, data.carY, data.carX)
        //刷新该页面
        RxJavaManager.getInstance().setTimer(1000) {
            data.zqId?.let { handleViewModel.loadDisasterDetail(it) }
        }

        if (!StringUtils.isEmpty(data.carY.toString()))
            carZZLocation = LatLng(data.carY, data.carX)
        if (carZZLocation != null) {
            uploadNavStateAdapter(7)
//            //上marker
            MapOperationEventPool.get()
                .sendDispatch(MapEvent(carZZLocation!!, LocationType.LOCATION_COMBAT, true))
//            //直接跳转导航界面
//            NavActivity.startNavActivity(FastStackUtil.getInstance().current, carZZLocation!!.latitude, carZZLocation!!.longitude)
        }
    }

    override fun onMessageJjdLocation(data: EventEntity.MessageDetailEvent) {
           super.onMessageJjdLocation(data)
        if (data.zqId == carZzxx?.zqxx?.id){
            //刷新当前的详情
            handleViewModel.loadDisasterDetail(carZzxx?.zqxx?.id!!)
        }


    }

    fun uploadNavStateAdapter(i: Int) {
        mAdapter.getItem(i)?.enable = true
        mAdapter.notifyItemChanged(i)
    }

    fun getJjdPosition(positon: Int): LatLng? {
        if (jjdXY_List != null && !StringUtils.isEmpty(jjdXY_List?.get(positon)?.xy)) {
            var str = ""
            if (jjdXY_List?.get(positon)?.xy?.startsWith("[[")!!){
                str = jjdXY_List?.get(positon)?.xy?.substring(2, jjdXY_List?.get(positon)?.xy?.length!! - 2)!!

            } else if (jjdXY_List?.get(positon)?.xy?.startsWith("[")!!){
                str = jjdXY_List?.get(positon)?.xy?.substring(1, jjdXY_List?.get(positon)?.xy?.length!! - 1)!!
            }
            var arrayXY = str!!.split(",")
            if (arrayXY.isNotEmpty()) {
                return LatLng(StringUtils.getStringNoKuohao(arrayXY[1]).toDouble(), StringUtils.getStringNoKuohao(arrayXY[0]).toDouble())
            }
        }
        return null
    }

    private fun showJjdPopWindow(view: View, position: Int, list: ArrayList<JjdItem>) {
        if (view != null) {
            var width_text = view.findViewById<RadiusTextView>(R.id.rtv_text).width
            var view_POP: View = getLayoutInflater().inflate(R.layout.layout_jjd_popwindow, null);
            var rv_jjd: RecyclerView = view_POP.findViewById<RecyclerView>(R.id.rv_jjd)
            if (pop == null) {
                rv_jjd.layoutManager = LinearLayoutManager(mContext)
                var adapter_jjd = JjdPopwindowAdapter(mContext, list)
                rv_jjd.adapter = adapter_jjd
                adapter_jjd.notifyDataSetChanged()
                adapter_jjd.setOnJjdClick(object : OnJjdClickLisenter {
                    override fun setOnclick(data: JjdItem, position: Int) {
                        pop!!.dismiss()
                        getJjdPosition(position)?.let {
                            //直接导航-
                            NavActivity.startNavActivity(
                                FastStackUtil.getInstance().current,
                                it!!.latitude,
                                it!!.longitude
                            )
                        }
                    }
                })
                pop = PopupWindow(
                    view_POP,
                    width_text,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    true
                );
                pop!!.setOutsideTouchable(true);
                pop!!.setOnDismissListener(object : PopupWindow.OnDismissListener {
                    override fun onDismiss() {
                        setBackgroundAlpha(1.0f)
                        mAdapter.getItem(position)?.common = true
                        mAdapter.notifyItemChanged(position)
                    }
                });
                jjdrecy_height = unDisplayViewSize(rv_jjd)
            }
            if (pop!!.isShowing()) {
                pop!!.dismiss();
            } else {
                mAdapter.getItem(position)?.common = false
                mAdapter.notifyItemChanged(position)
                setBackgroundAlpha(0.6f)
                pop!!.showAtLocation(
                    view,
                    0,
                    (view.left + ((view.width - width_text) / 2)).toInt(),
                    mContext.getWindowManager()
                        .getDefaultDisplay().height - view.bottom - jjdrecy_height!!
                )
            }
        }
    }

    private fun setBackgroundAlpha(fl: Float) {
        val params = mContext!!.window.attributes
        params.alpha = fl
        mContext.getWindow().setAttributes(params);
    }

    fun unDisplayViewSize(view: View): Int {
        val width = View.MeasureSpec.makeMeasureSpec(
            0,
            View.MeasureSpec.UNSPECIFIED
        )
        val height = View.MeasureSpec.makeMeasureSpec(
            0,
            View.MeasureSpec.UNSPECIFIED
        )
        view.measure(width, height)
        return view.measuredHeight
    }
}
